package eu.gegenleitner.esspacc.gui;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;

import org.apache.xml.security.utils.Base64;

import eu.gegenleitner.esspacc.communication.Messages;
import eu.gegenleitner.esspacc.xmlSignature.XMLSignatureRequester;
import eu.gegenleitner.esspacc.xmlSignature.XMLSignatureVerifier;

public class RunnableCertificateRequester implements Runnable{

	private MainWindow mainWindow;
	private String csr;
	
	public RunnableCertificateRequester(MainWindow window) {
		this.mainWindow = window;
	}
	
	@Override
	public void run() {
		try {
			mainWindow.getBtnSubmitCertificateSigning().setEnabled(false);
			generateCSR();
			sendRequestToCAService();
		} catch (Exception e) {
			e.printStackTrace();
			mainWindow.addLineToUserInfo("[ERROR]", false);
			mainWindow.addLineToUserInfo(e.getMessage(), true);
		}
	}
	
	private void generateCSR() throws NoSuchAlgorithmException {
		/*TODO: InputValidation*/
		String eMailAddress = mainWindow.getEMailTextField().getText();
		String givenName = mainWindow.getGNameTextField().getText();
		String surName = mainWindow.getSNameTextField().getText();
		
		mainWindow.addLineToUserInfo("Generating RSA-KeyPair\t\t\t\t", true);
		KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
		keyGen.initialize(4092);
		KeyPair pair = keyGen.generateKeyPair();
		mainWindow.keyPair = pair;
		mainWindow.addLineToUserInfo("[DONE]", false);
		
		String finalCsr = "My Name is =givenname=" + givenName + "=/givenname= =surname=" + surName
						+ "=/surname= and I want a Certificate for my e-mail address =email=" + eMailAddress
						+ "=/email= with the PublicKey =pubkey=" + Base64.encode(pair.getPublic().getEncoded()) + "=/pubkey=.";
		this.csr = finalCsr;
	}
	
	private void sendRequestToCAService() throws Exception {
		XMLSignatureRequester req = new XMLSignatureRequester();
		XMLSignatureVerifier veri = new XMLSignatureVerifier();
		mainWindow.addLineToUserInfo("Sign CSR with Citizen Card\t\t\t", true);
		String csrSignature = req.getXMLSignature(csr);
		if( !veri.isXMLSignatureValid(csrSignature) ) {
			System.out.println(csrSignature);
			throw new Exception("[ERROR] CSR-Signature not valid !");
		}
		mainWindow.addLineToUserInfo("[DONE]", false);
		
		
		mainWindow.addLineToUserInfo("Send signed CSR to CA-Service\t\t\t", true);
		
		String response = mainWindow.hReq.sendCSRToService(csrSignature);
		if( !response.equals(Messages.mailSent) )
			throw new Exception(response);
		mainWindow.addLineToUserInfo("[DONE]", false);
		mainWindow.addLineToUserInfo("Check your EMailAddress' InBox for a Token!", true);
		mainWindow.getBtnSubmitCertificateSigning().setEnabled(false);
		mainWindow.getBtnSubmitToken().setEnabled(true);
		mainWindow.getEMailTextField().setEditable(false);
		mainWindow.getTokenTextField().setEditable(true);
	}

}
